<template>
	<el-card shadow="never">
		<el-form
            :inline="true"
            :model="state.queryForm"
            @keyup.enter="onSearch()">
			<el-form-item>
				<el-input
                    v-model="state.queryForm.name"
                    placeholder="附件名称">
                </el-input>
			</el-form-item>
			<el-form-item>
				<el-input
                    v-model="state.queryForm.platform"
                    placeholder="存储平台">
                </el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="onSearch()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-upload
                    :action="uploadUrl"
                    :before-upload="beforeUpload"
                    :on-success="onSuccess"
                    :show-file-list="false">
					<el-button type="primary">上传</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item>
				<el-button type="danger" @click="deleteBatch()">删除</el-button>
			</el-form-item>
		</el-form>
		<el-table
            v-loading="state.loading"
            :data="state.dataList"
            style="width: 100%"
            @selection-change="selectionIds"
            border >
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column prop="name" label="附件名称" show-overflow-tooltip header-align="center" align="center">
                <template #default="scope">
					<!-- <img 
						v-if="scope.row.url && isImage(scope.row.name)"
						:src="getThumbnailUrl(scope.row.url)" 
						style="max-width: 50px; max-height: 50px;"
						:alt="scope.row.name"
						@click="previewImage(scope.row.url)">
					<span v-else>{{ scope.row.name }}</span> -->
                    <div class="thumbnail-wrapper" @click="previewImage(scope.row.url)">
                        {{ scope.row.name }}
                        <!-- <div v-if="scope.row.url && isImage(scope.row.name)" class="thumbnail-tooltip">
                            <img :src="getThumbnailUrl(scope.row.url)" :alt="scope.row.name">
                        </div> -->
                    </div>
				</template>
			</el-table-column>
			<el-table-column prop="url" label="附件地址" show-overflow-tooltip header-align="center" align="center"></el-table-column>
			<el-table-column prop="size" label="附件大小" header-align="center" align="center">
				<template #default="scope">
					{{ sizeFormat(scope.row.size) }}
				</template>
			</el-table-column>
			<el-table-column prop="platform" label="存储平台" header-align="center" align="center"></el-table-column>
			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center">
                <template #default="scope">
                    {{ scope.row.createTime.replace('T', ' ').split('+')[0] }}
                </template>
            </el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
				<template #default="scope">
					<el-button type="primary" link @click="onDownload(scope.row.url, scope.row.name)">下载</el-button>
					<el-button type="primary" link @click="deleteBatch(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

        <!-- 分页 -->
        <div style="margin-top: 20px;">
            <el-pagination
                layout="prev, pager, next"
                v-model:current-page="pagination.page"
                :page-size="pagination.limit"
                :total="pagination.total"
                @current-change="onPageChange"
                background
            >
            </el-pagination>
        </div>
	</el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { sizeFormat } from '@/utils/tools'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAttPage, deleteAtt } from '@/api/attachment.js'
import axios from 'axios'

// 文件上传地址
const token = ref(localStorage.getItem('token'))
// console.log(token.value)
const uploadUrl = import.meta.env.VITE_API_BASE_URL + '/api/sys/file_upload?access_token=' + token.value

const state = reactive({
    queryForm: {
        name: '',
        platform: '',
    },
    loading: false,
    dataList: []
})
const pagination = reactive({
	page: 1, 
	limit: 10, 
	total: 0, 
})

onMounted(() => {
    getDataList()
})

const getDataList = async() => {
    state.loading = true
    try {
        const query = {
            page: pagination.page, 
            limit: pagination.limit, 
            ...state.queryForm
        }
        const res = await getAttPage(query)
        state.dataList = res.list
        pagination.total = res.total
    } catch(error) {
        console.log(error)
    } finally {
        state.loading = false
    }
}

const keyIds = ref([])
const selectionIds = (selection) => {
    keyIds.value = selection.map((item) => item.id)
}

const onSearch = () => {
	pagination.page = 1
	getDataList()
}

const onPageChange = (val) => {
	pagination.page = val 
	getDataList() 
}

const deleteBatch = async(key) => {
    const ids = key ? [key] : keyIds.value
    if (ids.length === 0) {
      ElMessage.warning('请选择删除记录')
      return
    }

    try {
        await ElMessageBox.confirm('确定进行删除操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 获取要删除的文件URL列表
        const filesToDelete = state.dataList.filter(item => ids.includes(item.id))
        console.log(filesToDelete)
        // 先删除数据库记录
        await deleteAtt(ids)

        // 然后删除物理文件
        for(const file of filesToDelete) {
            try {
                await service.delete('/api/sys/file_delete', {
                    params: { fileUrl: file.url }
                })
            } catch(e) {
                console.error(`删除文件失败: ${file.url}`, e)
            }
        }

        ElMessage.success('删除成功')
        getDataList()
    } catch(error) {
        if(error !== 'cancel') { 
            ElMessage.error(error.message || '删除失败')
        }
    } 
}

const onDownload = async(url, filename) => {
    // 提取相对路径部分
    let filePath = url;
    if (url.startsWith(import.meta.env.VITE_UPLOAD_URL)) {
        filePath = url.replace(import.meta.env.VITE_UPLOAD_URL + '/', '');
    } else if (url.startsWith('http://') || url.startsWith('https://')) {
        filePath = url.split('/').slice(3).join('/');
    }

    try {
        const res = await axios({
            responseType: 'blob',
            url: `${import.meta.env.VITE_API_BASE_URL}/api/down_file?action=downFile&filePath=${filePath}&access_token=${token.value}`,
            method: 'post',
            // data: {
            //     action: 'downFile',
            //     filePath: filePath,  // 只传相对路径
            //     // access_token: token.value
            // }
        })
        const down = document.createElement('a')
        down.download = filename || Date.now().toString()
        down.style.display = 'none'
        down.href = URL.createObjectURL(new Blob([res.data]))
        document.body.appendChild(down)
        down.click()
        URL.revokeObjectURL(down.href)
        document.body.removeChild(down)
    } catch (err) {
        if (err.response?.status === 403) {
            ElMessage.error('无法下载,暂无权限')
        } else {
            ElMessage.error(err.message)
        }
    }


    /*console.log('地址：', url)
    // const res = await downFile(url)

    // console.log('res：', res)
    // 构造下载URL，只传递filePath参数
    const downloadUrl = `/api/down_file?filePath=${encodeURIComponent(url)}`
    window.open(downloadUrl, '_blank') */
}

// 图片功能 上传前校验方法
const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('只能上传图片文件')
		return false
    }

	if (file.size / 1024 / 1024 / 1024 > 1) {
		ElMessage.error('文件大小不能超过10M')
		return false
	}
	return true
}

const onSuccess = (response, file) => {
    // console.log(response)
	if (response.code !== 0) {
		ElMessage.error('上传失败：' + response.msg)
		return false
	}
    
	ElMessage.success({
		message:  file.name + '上传成功',
		duration: 500,
		onClose: () => {
			getDataList()
		}
	})
    /*
    imageUrl = response.data.url
    pictureList.value = [{
        uid: file.uid,
        name: file.name,  
        url: `${uploadUrl}/uploads/${response.data.url}`,
        status: 'done' // 确保状态为done
    }]
    message.success('上传成功')
    */
}

// 增加 缩略图功能
const isImage = (fileName) => {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
  return imageExtensions.some(ext => fileName.toLowerCase().endsWith(ext))
}

const getThumbnailUrl = (url) => {
    const path = import.meta.env.VITE_UPLOAD_URL + '/' + url
    console.log(path)
  // 这里可以根据实际情况生成缩略图URL
  // 例如添加缩略图参数或调用缩略图服务
  return path + '?thumb=50x50'
}

const previewImage = (url) => {
    // 检测url是否是绝对路径，如果不是则加上前缀
    let path = url
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        path = import.meta.env.VITE_UPLOAD_URL + '/' + url
    }

    // const path = import.meta.env.VITE_UPLOAD_URL + '/' + url
    
  // 实现图片预览逻辑
  ElMessageBox.alert(`<img src="${path}" style="max-width: 50%">`, '图片预览', {
    dangerouslyUseHTMLString: true,
    customClass: 'image-preview-modal'
  }).catch(() => {})
}
</script>

<style lang="scss" scoped>
.thumbnail-wrapper {
    position: relative;
    display: inline-block;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    
    .thumbnail-tooltip {
        position: absolute;
        bottom: 100%;
        left: 50%;
        transform: translateX(-50%);
        padding: 8px;
        background: #fff;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        z-index: 9999;
        display: none !important;
        min-width: 150px;
        min-height: 150px;
        
        img {
            max-width: 150px;
            max-height: 150px;
            object-fit: contain;
            display: block;
        }
    }
    
    &:hover .thumbnail-tooltip {
        display: block!important;
    }
}
</style>